class BarsController < ApplicationController
  layout "default"
  
  def index
    list
    render :action => 'list'
  end

  verify :method => :post, :only => [ :destroy, :create, :update, :do_action,
                                      :add_visitor ],
         :redirect_to => { :action => :list }

  def list
    @bar_pages, @bars = paginate :bars, :per_page => 10
  end

  def show
    @bar = Bar.find(params[:id])
    @todays_visitors = BarVisitor.find_by_sql("select * from bar_visitors where " + 
                                              "DATEDIFF(created_at, CURDATE()) = 0 and " + 
                                              "bar_id = #{params[:id]}")
    @feed = BarFeed.find(:all, :conditions => ["bar_id = ?", params[:id]], 
                               :order => "created_at DESC",
                               :limit => 15)
  end

  def new
    if request.post?
      create
    else
      @bar = Bar.new
    end
  end

  def create
    @bar = Bar.new(params[:bar])
    if @bar.save
      flash[:notice] = 'Die Bar wurde erfolgreich angelegt.'
      redirect_to :action => 'show', :id => @bar.id
    else
      render :action => 'new'
    end
  end

  def edit
    @bar = Bar.find(params[:id])
  end

  def update
    @bar = Bar.find(params[:id])
    if @bar.update_attributes(params[:bar])
      flash[:notice] = 'Bar was successfully updated.'
      redirect_to :action => 'show', :id => @bar
    else
      render :action => 'edit'
    end
  end

  def add_visitor
    # Check for existing entry
    duplicate = BarVisitor.find_by_sql("select * from bar_visitors where " + 
                                       "DATEDIFF(created_at, CURDATE()) = 0" + 
                                       " and bar_id = #{params[:id]}" + 
                                       " and user_id = #{session[:user_id]}" + 
                                       " limit 1 ")
    if duplicate.blank?
      visitor = BarVisitor.new
      visitor.bar_id = params[:id]
      visitor.user_id = session[:user_id]
      if visitor.save!
        flash[:success] = "Du wurdest erfolgreich als Besucher eingetragen"
        BarFeed.add_action(params[:id], session[:user_id], 9)
      else
        flash[:notice] = "Es ist ein Fehler aufgetreten!"
      end
    else
      flash[:notice] = "Du bist heute bereits eingetragen!"
    end
    
    redirect_to_bar
  end
  
  def do_action
    BarFeed.add_action(params[:id], session[:user_id], params[:a])
    
    flash[:success] = "Aktion erfolgreich eingetragen!"
    redirect_to_bar
  end
  
  def add_coworker
    if BarCoworker.add(params[:id], session[:user_id])
      BarFeed.add_action(params[:id], session[:user_id], 7)
      flash[:success] = "Du wurdest erfolgreich als Mitarbeiter eingetragen!"
    else
      flash[:error] = "Du bist bereits als Mitarbeiter eingetragen!"
    end
    redirect_to_bar
  end
  
  private
  
  def redirect_to_bar(id = params[:id])
    redirect_to :action => :show, :id => id
  end
end
